package com.citrix.gs.util.beacon;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


@SuppressWarnings({"rawtypes"})
public class BeaconServer {

    private static Logger logger = LoggerFactory.getLogger(BeaconServer.class);
            
    // The client used to access beacon rest apis
    private BeaconHttpClient restClient = null;
    private BeaconHttpClient shortLinkClient = null;
    private final String shortLinkServiceURL = "http://gaas.eng.citrite.net:5000/";
    
    public BeaconHttpClient getRestClient() {
        return restClient;
    }

    public void setRestClient(BeaconHttpClient restClient) {
        this.restClient = restClient;
    }

    public BeaconHttpClient getShortLinkClient() {
        return shortLinkClient;
    }

    public void setShortLinkClient(BeaconHttpClient shortLinkClient) {
        this.shortLinkClient = shortLinkClient;
    }
    
    public BeaconServer(String restUri) throws URISyntaxException {
        this(new URI(restUri));
    }

    public BeaconServer(URI restUri) {
        
        restClient = new BeaconHttpClient(restUri);
        try {
            shortLinkClient = new BeaconHttpClient(new URI(shortLinkServiceURL));
        } catch (URISyntaxException e) {
            logger.error("Construct short link service client fail: ", e);
        }
    }
    
    public String getShortLink(String longLinkUrl) {
        
        String shortId = "";
        
        try {
            shortId = shortLinkClient.get("s/" + longLinkUrl);
        } catch (IOException e) {
            logger.error("Get short link id fail: ", e);
        }
        
        return shortLinkServiceURL + "r/" + shortId;
    }
    
    public List getRepositories() throws IOException {
        return restClient.getList("repositories/");
    }
    
    public JSONArray getRepoArray() throws IOException {
        return restClient.getJsonArray("repositories/");
    }
    
    public JSONObject getRepository(String repo) throws IOException {
        return restClient.getJsonObject("repository/" + repo);
    }
    
    public JSONArray getIssuesInRepo(String repo) throws IOException {
        JSONObject repoJson = getRepository(repo);
        
        return repoJson.getJSONArray("issues");
    }
    
    public JSONArray getIssuesInRepo(String repo, String errorCode) throws IOException {
        JSONArray issues = getIssuesInRepo(repo);
        return new JSONArray(issues
                .stream()
                .filter(i -> ((JSONObject)i).getString("code").equalsIgnoreCase(errorCode))
                .collect(Collectors.toList()));
    }
    
    public List<String> getRevisionsWithError(String repo, String errorCode) throws IOException {
        JSONArray issues = getIssuesInRepo(repo, errorCode);
        
        return issues.stream().map((Object i) -> {
            JSONObject t = (JSONObject)i;
            return t.getJSONArray("revisions");
        }).flatMap((JSONArray revs) -> revs.stream())
        .distinct()
        .map(o -> o.toString())
        .collect(Collectors.toList());
    }
    
    
    public static void main(String[] args) {
        
        try {
            BeaconServer beacon = new BeaconServer(new URI("http://nkggsportal.eng.citrite.net:1111/api/2/"));
            
            List repositories = beacon.getRepositories();
            
            System.out.println(repositories.size());
            
            JSONArray repoArray = beacon.getRepoArray();
            
            System.out.println(repoArray.size());
            int size = repoArray.size();
             
            for(int i=0; i<size; i++) {
                JSONObject repo = repoArray.getJSONObject(i);
                System.out.println(repo.getString("_id"));
            }
            
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}
